package com.wctj.api.business.common.listener;

import com.wctj.api.business.common.component.AsyncTransactionalEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * 异步执行事务事件 通用监听器
 *
*/
 @Slf4j
 @Component
 public class AsyncTransactionalEventListener {
    @Resource
    private TransactionalEventExecutor transactionalEventExecutor;

    @Async("zgzgTaskExecutor")
    @TransactionalEventListener(fallbackExecution = true)
    public void onApplicationEvent(AsyncTransactionalEvent asyncTransactionalEvent) {
        log.info("收到了异步事务任务，source:{},id:{}", asyncTransactionalEvent.getSource(), asyncTransactionalEvent.getId());
        try {
            transactionalEventExecutor.exec(asyncTransactionalEvent.getTask());
        } catch (Exception e) {
            log.error("执行异步事务监听任务失败 source:{}, id:{}", asyncTransactionalEvent.getSource(), asyncTransactionalEvent.getId(),e);
            throw e;
        }finally {
//            UserContext.removeContextUserWithFeignHeader();
            log.debug("结束--- source:{} eventId: {}", asyncTransactionalEvent.getSource(), asyncTransactionalEvent.getId());
        }
    }

}
